package edu.uwm.cs552.util;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;


public final class MouseHoverListenerAdapter extends MouseAdapter implements Runnable {

	public static void addHoverListener(JComponent c, MouseHoverListener l) {
		MouseHoverListenerAdapter a = new MouseHoverListenerAdapter(l);
		c.addMouseListener(a);
		c.addMouseMotionListener(a);
	}
	
	private final MouseHoverListener listener;
	private boolean waiting = false;
	private boolean hovering = false;
	private long lastMoved = 0;
	private MouseEvent lastEvent = null;
	
	public MouseHoverListenerAdapter(MouseHoverListener l) {
		listener = l;
		Clock.getInstance().addListener(this, MouseHoverListener.HOVER_WAIT);
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		stopHover(arg0);
		waiting = true;
		lastMoved = System.currentTimeMillis();
		lastEvent = arg0;
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		stopHover(arg0);
		waiting = false;
		lastEvent = null;
	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
		stopHover(arg0);
		waiting = true;
		lastMoved = System.currentTimeMillis();
		lastEvent = arg0;
	}
	
	private void stopHover(MouseEvent arg) {
		if (hovering) {
			listener.mouseHoverStop(arg);
			hovering = false;
		}
	}
	public void run() {
		if (waiting && (System.currentTimeMillis() - lastMoved) > MouseHoverListener.HOVER_WAIT) {
			listener.mouseHoverStart(lastEvent);
			hovering = true;
			waiting = false;
			lastEvent = null;
		}
	}
}
